const { JSDOM } = require("jsdom");

const { replaceAttribute, removeElementsBySelectors } = require("../utils.js");

module.exports = getContent;

function getContent(url) {
  return JSDOM.fromURL(url).then((dom) => {
    let document = dom.window.document;

    let imgSrc = document
      .querySelector('meta[property="og:image"]')
      .getAttribute("content");
    let img = document.createElement("img");
    img.setAttribute("src", imgSrc);

    // 插入图片，移除id
    let story = document.getElementById("js-article-read-wrap");
    story.insertAdjacentElement("afterbegin", img);
    story.removeAttribute("id");

    // 将 _src 替换成 src
    story.querySelectorAll("img[_src]").forEach((el) => {
      replaceAttribute(el, "_src", "src");
    });

    // 标题降低： h1 -> h2
    let h1 = story.querySelector(".article__title");
    let h2 = document.createElement("h2");
    h2.textContent = h1.textContent;
    h1.insertAdjacentElement("beforebegin", h2);
    h1.remove();

    // 将所有的 .text-remarks 换成 i 标签
    story.querySelectorAll(".text-remarks").forEach((mk) => {
      let i = document.createElement("i");
      i.textContent = mk.textContent;
      mk.insertAdjacentElement("beforebegin", i);
      mk.remove();
    });

    let excludes = [
      "iframe",
      "script",
      "input",
      "button",
      "img:not([src], [src=''])", // 移除没有指定地址的图片
      ".article__author-info-box",
    ];
    removeElementsBySelectors(story, excludes);

    story.querySelectorAll("[class], [id], [style]").forEach((e) => {
      e.removeAttribute("class");
      e.removeAttribute("id");
      e.removeAttribute("style");
    });

    // 移除所有gif图片
    story.querySelectorAll("img").forEach((el) => {
      let src = el.getAttribute("src"),
        regx = /\.gif\s?$|\.gif\s?\?/i;
      if (regx.test(src)) el.remove();
    });

    // 移除类似：data-v-7c17b2a8 的编译信息
    Object.values(story.attributes).forEach((attr) => {
      let regx = /^data/i;
      attr = attr.name;
      if (regx.test(attr)) {
        story.removeAttribute(attr);
        story
          .querySelectorAll("[" + attr + "]")
          .forEach((el) => el.removeAttribute(attr));
      }
    });

    // <o:p></o:p>
    // <p><br ></p>
    //<!---->
    let title = h2.textContent;
    let data = story.outerHTML
      .replace(/<o:p>\s?<\/o:p>/g, "")
      .replace(/<p>\s?<br\s?>\s?<\/p>/g, "")
      .replace(/<!--*?-->/g, "");

    return {
      title,
      data,
    };
  });
}
